# Create your views here.
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
import django.utils.simplejson as json
import django.utils.webhelpers as webhelpers
from django.http import HttpResponse, Http404, HttpResponseRedirect

from django.contrib.auth.models import User, Group
from usecaseapp.models import Usecase
from random import randrange
from usecase import settings
from django.contrib import logging
logger = logging.getLogger('usecase')


class UserState(object):
    def __init__(self, request):
        default = {}
        default['isloggedin'] = False
        default['isactive'] = False
        default['isstaff'] = False
        default['error'] = False #just a flag you set if 'message' is an error
        self.state = request.session.get('userstate', default)
        self.request = request

    def extract(self):
        '''Pull the record from the session. Then deletes it.'''
        request = self.request
        ret = None
        if request.session.has_key('userstate'):
            ret = request.session.get('userstate')
            del request.session['userstate']
        else:
            ret = UserState().state

        if not ret.has_key('message'):
            ret['message'] = False
        return ret

    def update(self, message=False, error=None):
        request = self.request
        userobject = request.user
        if userobject is not None:
            self.state['isloggedin'] = userobject.is_authenticated()
            self.state['isactive'] = userobject.is_active
            self.state['isstaff'] = userobject.is_staff
            if message:
                self.state['message'] = message
            if error is not None:
                self.state['error'] = error

        #store on the session
        request.session['userstate'] = self.state
        return self
        


def display_random_usecase(request):
    description = ""
    submitter = ""
    userstate = UserState(request).update().extract()
    try:
        postersgroup = Group.objects.get(name="UsecasePosters")
        #usecases = Usecase.objects.filter(submitter in postersgroup.user_set and submitter__is_active=True)
        usecases = Usecase.objects.filter(submitter__is_active=True).filter(submitter__in=postersgroup.user_set.values_list('id'))
        randnum = randrange(usecases.count())#no need to -1, because of randrange
        usecase = usecases[randnum]
        description = usecase.description
        submitter = usecase.submitter.get_full_name()
    except Exception, e:
        logger.warning("Error displaying main page: %s" % ( e ) )
        description = "Sorry, the service is unavailable"
        submitter = "Try again later"
    
    message = userstate['message']

    return render_to_response("usecaseapp/displayusecase.html", {'description' : description, 'submitter' : submitter, 'userstate':userstate, 'message' : message, 'error' : userstate.get('error', False), 'wh' : webhelpers }, context_instance=RequestContext(request))

def submit_usecase(request):
    submitted_text = request.POST.get('submittext', None)
    message = ""
    if not request.user.is_authenticated():
        message = "You need to be logged in to post a suggestion"
    else:
        if submitted_text is not None:
            try:
                newusecase = Usecase()
                newusecase.description = submitted_text
                newusecase.submitter = request.user
                newusecase.save()
                message = "Thankyou for your suggestion"
            except Exception, e:
                message =  "Problem submitting: %s" % (e)
    
    UserState(request).update(message=message)
    return HttpResponseRedirect(webhelpers.url("/"))

def login_user(request):
    state = "Please log in below..."
    username = password = ''
    error = False
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "Welcome back %s" % (user.first_name)
            else:
                state = "Your account is not yet active. Check for activation email."
                error = True
        else:
            state = "Your username and/or password were incorrect."
            error = True

    #return render_to_response('auth.html',{'state':state, 'username': username})
    #return HttpResponse(json.dumps({'state': state, 'username': username}))
    UserState(request).update(message=state, error=error)
    return HttpResponseRedirect(webhelpers.url("/"))

def logout_user(request):
    logout(request)
    return HttpResponseRedirect(webhelpers.url("/"))
